<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AILabel-标注篇</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
    <script src='../index.js'></script>

    <style type="text/css">
        body {
            padding: 10px 20px;
        }
        .button-wrap {
            padding-bottom: 10px;
        }
        #map {
            overflow: hidden;
            position: relative;
            height: 600px;
            border: 1px dashed #ccc;
        }
        .zoom-icon-wrapper {
            position: absolute;
            left: 20px;
            top: 20px;
            z-index: 1000;
        }
        .zoom-icon-plus {
            width: 30px;
            height: 30px;
            line-height: 20px;
            text-align: center;
            border: 3px solid #6495ED;
            font-size: 20px;
            border-top-left-radius: 6px;
            border-top-right-radius: 6px;
            color: #FF8C00;
            cursor: pointer;
        }
        .zoom-icon-plus:hover {
            border-color: #4169E1;
        }
        .zoom-icon-minus {
            margin-top: 6px;
            width: 30px;
            height: 30px;
            line-height: 20px;
            text-align: center;
            border: 3px solid #6495ED;
            font-size: 25px;
            border-bottom-left-radius: 6px;
            border-bottom-right-radius: 6px;
            color: #FF8C00;
            cursor: pointer;
        }
        .zoom-icon-minus:hover {
            border-color: #4169E1;
        }
    </style>
</head>
<body>
    <div class="button-wrap">
        <button class="btn btn-default" onclick="setMode('PAN');">平移</button>
        <button class="btn btn-default" onclick="setMode('RECT');">矩形</button>
        <button class="btn btn-default" onclick="switchImage();">下一张</button>
        &nbsp;&nbsp;
        <a href="../index.html" target="_blank">>>详细demo</a>
    </div>

    <div id="map">
        <div class="zoom-icon-wrapper">
            <div class="zoom-icon-plus" onclick="zoomIn();">+</div>
            <div class="zoom-icon-minus"  onclick="zoomOut();">-</div>
        </div>
    </div>

    <br/>

    <div>注：在绘制模式（点/线/面）时，双击图形可进行选中编辑；单击未选中图形区域或切换mode模式会取消选中</div>

    <script>
        let drawingStyle = {}; // 绘制过程中样式
        const dpr = window.devicePixelRatio;
        const images = [
            {src: '../bg.webp', zoom: 800, center: {x: 250, y: 177}, width: 500, height: 354},
            {src: './bg2.jpeg', zoom: 1500, center: {x: 600, y: 397.5}, width: 1200, height: 795},
            {src: './libai.jpeg', zoom: 800, center: {x: 320, y: 160.5}, width: 640, height: 321},
            {src: './zhangliang.jpeg', zoom: 800, center: {x: 375, y: 210.5}, width: 750, height: 421}
        ];
        let index = 0; // 当前图片的index
        function getNextImage() {
            const currentIndex = index;
            // 重新计算index
            index = (index + 1) >= images.length ? 0 : (index + 1);
            // 返回图片信息
            return images[currentIndex];
        }

        const gMap = new AILabel.Map('map', {
            center: {x: 250, y: 177}, // 为了让图片居中
            zoom: 800,
            mode: 'PAN', // 绘制线段
            refreshDelayWhenZooming: true, // 缩放时是否允许刷新延时，性能更优
            zoomWhenDrawing: true,
            panWhenDrawing: true
        });

        gMap.events.on('drawDone', (type, data, data1) => {
            console.log('--data--', data);
            const relatedTextId = `label-text-id-${+new Date()}`;
            const relatedDeleteMarkerId = `label-marker-id-${+new Date()}`;
            if (type === 'RECT') {
                // 添加feature
                const rectFeature = new AILabel.Feature.Rect(
                    `${+new Date()}`, // id
                    data, // shape
                    {name: '矢量图形', textId: relatedTextId, deleteMarkerId: relatedDeleteMarkerId}, // props
                    drawingStyle // style
                );
                gFirstFeatureLayer.addFeature(rectFeature);
                // 添加feature标签名
                const {x: ltx, y: lty} = data;
                const gFirstText = new AILabel.Text(
                    relatedTextId, // id
                    {text: '铅笔', position: {x: ltx, y: lty}, offset: {x: 0, y: 0}}, // shape, 左上角
                    {name: '第一个文本对象'}, // props
                    {fillStyle: '#F4A460', strokeStyle: '#D2691E', background: true, globalAlpha: 1, fontColor: '#0f0'} // style
                );
                gFirstTextLayer.addText(gFirstText);
            }
        });

        gMap.events.on('featureSelected', feature => {
            // 高亮选中feature
            gMap.setActiveFeature(feature);
            const markerId = feature.props.deleteMarkerId;
            const textId = feature.props.textId;

            const mappedMarker = gMap.markerLayer.getMarkerById(markerId);
            if (mappedMarker) {
                return;
            }

            // 添加delete-icon
            const gFirstMarker = new AILabel.Marker(
                markerId, // id
                {
                    src: './delete.png',
                    position: feature.getPoints()[1], // 矩形右上角
                    offset: {
                        x: -20,
                        y: -4
                    }
                }, // markerInfo
                {name: '第一个marker注记'} // props
            );
            gFirstMarker.events.on('click', marker => {
                // 首先删除当前marker
                gMap.markerLayer.removeMarkerById(marker.id);
                // 删除对应text
                gFirstTextLayer.removeTextById(textId);
                // 删除对应feature
                gFirstFeatureLayer.removeFeatureById(feature.id);
            });

            gMap.markerLayer.addMarker(gFirstMarker);
        });
        gMap.events.on('featureUnselected', feature => {
            gMap.setActiveFeature(null);
            gMap.markerLayer.removeMarkerById(feature.props.deleteMarkerId);
        });
        gMap.events.on('featureUpdated', (feature, shape) => {
            feature.updateShape(shape);

            const markerId = feature.props.deleteMarkerId;
            const textId = feature.props.textId;
            // 更新marker位置
            const targetMarker = gMap.markerLayer.getMarkerById(markerId);
            targetMarker.updatePosition(feature.getPoints()[1]);
            // 更新text位置
            const targetText = gFirstTextLayer.getTextById(textId);
            console.log('--targetText--', targetText);
            targetText.updatePosition(feature.getPoints()[0]);
        });

        // feature-层
        const gFirstFeatureLayer = new AILabel.Layer.Feature(
            'first-layer-feature', // id
            {name: '第一个矢量图层'}, // props
            {zIndex: 10} // style
        );
        gMap.addLayer(gFirstFeatureLayer);

        // text-层
        const gFirstTextLayer = new AILabel.Layer.Text(
            'first-layer-text', // id
            {name: '第一个文本图层'}, // props
            {zIndex: 12, opacity: 1} // style
        );
        gMap.addLayer(gFirstTextLayer);

        function setMode(mode) {
            gMap.setMode(mode);
            // 后续对应模式处理
            switch (gMap.mode) {
                case 'PAN': {
                    break;
                }
                case 'RECT': {
                    drawingStyle = {strokeStyle: '#00f', lineWidth: 1}
                    gMap.setDrawingStyle(drawingStyle);
                    break;
                }
                default:
                    break;
            }
        }

        // 切换图片
        let gFirstImageLayer;
        function switchImage() {
            // 图片层添加
            const initImage = getNextImage();
            gFirstImageLayer && gMap.removeLayerById('first-layer-image');

            gFirstTextLayer.removeAllTexts();
            gFirstFeatureLayer.removeAllFeatures();
            gMap.markerLayer.removeAllMarkers();

            // 实例化图片层
            gFirstImageLayer = new AILabel.Layer.Image(
                'first-layer-image', // id
                {
                    src: initImage.src,
                    width: initImage.width,
                    height: initImage.height,
                    position: { // 左上角相对中心点偏移量
                        x: 0,
                        y: 0
                    },
                    grid: { // 3 * 3
                        columns: [{color: '#9370DB'}, {color: '#FF6347'}],
                        rows: [{color: '#9370DB'}, {color: '#FF6347'}]
                    }
                }, // imageInfo
                {name: '第一个图片图层'}, // props
                {zIndex: 5} // style
            );
            gMap.addLayer(gFirstImageLayer);

            gMap.centerAndZoom({center: initImage.center, zoom: initImage.zoom});
        }
        switchImage();

        window.onresize = function() {
            gMap && gMap.resize();
        }
    </script>

<!-- 百度统计代码添加 -->
<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?d662d8c3f35f9f124a998a7dd5e24835";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>
</body>
</html>
